package de.openlaboratory.labhub.core.server.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import de.openlaboratory.labhub.core.Application;
import de.openlaboratory.labhub.core.ApplicationResources;
import de.openlaboratory.labhub.core.framework.Helper;
import de.openlaboratory.labhub.core.framework.LabHubApplication;

public class DefaultRequestDispatcher implements RequestDispatcher
{
	@Override
	public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException
	{
		// LabHubApplication app = ApplicationResources.getLabHubApplication(request);
		
		String defaultLayout = getDefaultLayout();
		// InputSource defaultLayoutInputSource = getDefaultLayoutInputSource();
		ArrayList<String> token = Helper.getTokens(defaultLayout);
		
		response.setContentType("text/html");

		ServletOutputStream out = response.getOutputStream();
		// Properties prop = new Properties();
		// InputStream in =
		// getClass().getResourceAsStream("defaultLayout.template");
		// InputStream in =
		// getClass().getResourceAsStream("/de/openlaboratory/labhub/core/server/servlet/defaultLayout.template");
		// prop.load(in);
		// in.close();
		// out.println(prop.getProperty("a"));

		// Properties p = new Properties();
		// p.load(DefaultRequestDispatcher.class.getResourceAsStream("/templates/defaultLayout.template"));
		// PropertyConfigurator.configure(p);
		out.print(Helper.join(token, ","));
		out.print(defaultLayout);
	}

	private String getDefaultLayout()
	{
		InputStream in;
		InputStreamReader inputReader;
		BufferedReader bufferedReader;
		String line;
		StringBuilder stringBuilder = new StringBuilder();

		try
		{
			in = getClass().getResourceAsStream("templates/defaultLayout.template");
			// getClass().getResource("defaultLayout.template");
			inputReader = new InputStreamReader(in);
			bufferedReader = new BufferedReader(inputReader);

			while ((line = bufferedReader.readLine()) != null)
			{
				stringBuilder.append(line + "\n");
			}

			bufferedReader.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		return stringBuilder.toString();
	}
	
	@Override
	public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
	}
}